package com.etymgiko.lyricshere.web;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.etymgiko.lyricshere.SettingsProvider;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.users.UserService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Ivan Holub
 */
public class DataInterceptor extends HandlerInterceptorAdapter {

    private SettingsProvider settingsProvider;

    public void setSettingsProvider(SettingsProvider settingsProvider) {
        this.settingsProvider = settingsProvider;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        RequestData d = new RequestData();
        if (user != null) {
            d.setSignedIn(true);
            d.setUserNickname(user.getNickname());
            d.setLogoutURL(userService.createLogoutURL("/"));
            if (settingsProvider.isAdmin(user.getEmail())) {
                d.setAdmin(true);
            }
        } else {
            d.setLoginURL(userService.createLoginURL("/"));
        }
        d.setCounterCode(settingsProvider.getCounterCode());
        request.setAttribute("requestData", d);
        return true;
    }
}